package cn.gson.crm.service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.gson.crm.model.dao.ReceivableDao;
import cn.gson.crm.model.dao.RemindDao;
import cn.gson.crm.model.entity.Receivable;
import cn.gson.crm.model.entity.Remind;

/**
 *
 * @author hzl
 * @date 2018年5月25日
 * @time 下午4:17:46
 */
// 自动装载
@Component
public class ReceivableService extends Thread {
	@Autowired
	ReceivableDao receivabledao;
	
	@Autowired
	RemindDao remindDao;

	// 新建全局变量,订单截止时间记录将存放在这里
	List<Receivable> receivablelist = new ArrayList<Receivable>();

	// 服务启动自动加载
	@PostConstruct
	public void init() {
		// 获取数据库存在的订单截止时间记录
		receivablelist=receivabledao.findByState("未回款");
		if(receivablelist.size()>0){
			// 开始线程
			this.start();
		}
	}

	// 重写run方法,this.start后将运行此方法
	@Override
	public void run() {
		Calendar calendar = Calendar.getInstance();  
		for (int i = 0; i < 1; i--) {
			try {
				// 每24个小时运行
				sleep(1000*60*60*24);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
//			timer.schedule(new MyTask(), 1000, 2000);
			//在1秒后执行此任务,每次间隔2秒执行一次,如果传递一个Data参数,就可以在某个固定的时间执行这个任务.  
			for (Receivable receivable : receivablelist) {
		        calendar.setTime(receivable.getPlanTime());  
		        calendar.add(Calendar.DAY_OF_MONTH, -1);  
				if(calendar.getTime().before(new Date())){
					//添加一条回款计划快过期的提醒
					remindDao.save(new Remind("有一条回款计划还有一天就过期了，快去看看", "回款", false,new Date(),receivable.getEmployee()));
				}else if(receivable.getPlanTime().before(new Date())){//如果超时
					receivable.setState("逾期未回");
					receivabledao.save(receivable);
					//添加一条添加一条回款计划过期的提醒
					remindDao.save(new Remind("有一条回款计划过期了，快去看看", "回款", false,new Date(),receivable.getEmployee()));
				}
			}
		}

	}

	// list中添加数据,创建订单时调用
	public void addReceivablEndPayTimeList(Receivable receivable) {
		receivablelist.add(receivable);
	}

	// list中删除数据,完成支付或者取消订单时调用
	public void removeReceivablEndPayTimeList(Receivable receivable) {
		if (receivablelist.contains(receivable)) {
			List<Receivable> removeList = new ArrayList<Receivable>();
			removeList.add(receivable);
			receivablelist.removeAll(removeList);
		}
	}
}
